/**
 * 
 */
package com.neusoft.cmsprojects.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

/**
 * index:
 * 
 * @author guanhaimin date:2014年12月17日下午3:32:34
 */
public class UeditorFilter implements Filter {

	 private List<String> list = new ArrayList<String>();
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Autowired
	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response=(HttpServletResponse)res;
		String path=((HttpServletRequest)request).getServletPath();
		//取得访问的路径
		String contextpath=request.getContextPath();
		for(int i=0;i<list.size();i++){
			//集合里面的值比较
            if(path.indexOf((String)list.get(i))!=-1){//需要拦截
            	//判断session里面是否有值，有放行。没有跳转到登陆界面
            	if(request.getSession().getAttribute("user")==null){
                    response.sendRedirect(contextpath+"/test.jsp"); 
            	}
            	else{
            		 chain.doFilter(req, res);  
            	}
            	break;
            }else{  
                chain.doFilter(req, res);  
            }  
        }  
		
		/*String url = request.getRequestURI();
		System.out.println(url);
		if (decideURI(url)) {
			chain.doFilter(new StrutsRequestWrapper((HttpServletRequest) req),res);
		} else {
			chain.doFilter(req, res);
		}*/
	}
	
	 /**
     * ueditor编辑器中的图片上传和文件上传
     * @param url
     * @return
     */
    private boolean decideURI(String url){
        if(url.endsWith("imageUp.jsp")){
            return true;
        }else {
        	if(url.endsWith("controller.jsp")){
        		return true;
        	}else{
        		return false;
        	}
        }
    }

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		//配置要拦截的文件夹
		String include = filterConfig.getInitParameter("jsp");
         if (include != null) { 
        	 //多个文件用都号隔开
                StringTokenizer st = new StringTokenizer(include, ",");
                list.clear();  
                while (st.hasMoreTokens()) {
                    list.add(st.nextToken());  
                }  
         }  

	}

}
